package com.muki.wareHouse;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.muki.base.BaseConfig;
import com.muki.base.PoolExector;

/**
 * 
 * @author ljh_2017
 *
 */
public class Corpus implements CorpusParser {

	//原文信息
	private String context;
	
	private String title;
	
	public Corpus(String title,String context) {
		//String[] titles = title.substring(title.indexOf(":")+1).replaceAll("/", "_").replaceAll(":", "_");
		int fin = title.indexOf(":");
		int lin = title.lastIndexOf("?");
		String url = lin!=-1 ? title.substring(fin+1,lin):title.substring(fin+1);
		String param = lin!=-1 ? "-"+title.substring(lin+1) : "#";
		this.title = url.replaceAll("/", "_").replace(":", "_")+param.replaceAll("=", "_").replaceAll(":", "_");
		this.context = context;
	}

	@Override
	public Path remoteSave(String ip, int port, String bath_path) {
		//routes.put(title, ip+":"+port+"//"+bath_path);
		return null;
	}

	@Override
	public Path localSave(String bath_path) {

		Path directory = Paths.get(bath_path);
		if(!Files.exists(directory)) {
			try {
				Files.createDirectory(directory);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String file = title+".html";
		try {
			RandomAccessFile afile = new RandomAccessFile(bath_path+file, "rw");
			FileChannel fc = afile.getChannel();
			ByteBuffer bf = ByteBuffer.allocate(BaseConfig.max_size);
			bf.clear();
			bf.put(context.getBytes());
			bf.flip();
			while(bf.hasRemaining()) {
				fc.write(bf);
			}
			fc.close();
			return Paths.get(bath_path+file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
